import json
import time
import urllib.request
import numpy as np
from multiprocessing import Process
import os
TestType = 'status' # track or status
def IOVPerformanceTest(TestType):
    ParentProcessID = os.getppid()
    ProcessID = os.getpid()

    #TargetServer = "10.4.0.60"
    TargetServer = "localhost"
    #TargetPort = "6388"
    TargetPort = "8091"
    StatusAPI = "/redis/queryVehicleInfoByTerminalCode"
    TrackAPI = "/redis/queryVehicleTrackInfoByTerminalCode"

    StatusURL = "http://"+TargetServer+":"+TargetPort+StatusAPI
    TrackURL = "http://"+TargetServer+":"+TargetPort+TrackAPI
    print("TestType:" + TestType)
    print("TargetServer:"+TargetServer+";TargetPort:"+TargetPort)
    print('测试父进程ID:'+str(ParentProcessID)+';测试进程PID:' + str(ProcessID))

    StatusBody = {
        "terminalCode": "LFPHC7PE1K1A06216,LFPHC7PE6K1A13713,LFPHC7PE3K1A06587,LFPHC7PE8K1A05600,LFPHC7PE0K1A06501,LFPHC7PE1K1A00982"}
    TrackBody = {"terminalCode":"LFPHC7PE1K1A06216","startTime":"2018-01-29 12:34:56","endTime":"2019-03-29 23:59:59"}


    TestURL =''
    TestBody =''
    if TestType=='status':
        TestURL = StatusURL
        TestBody = StatusBody
    elif  TestType=='track':
        TestURL = TrackURL
        TestBody = TrackBody

    print("TestURL:" + TestURL )

    TestTimes = 10
    TestTimeList = []

    for index in range(TestTimes):

        TestStartTime = time.time()
        #print("TestStartTime:"+str(TestStartTime))
        params = json.dumps(TestBody).encode('utf8')
        req = urllib.request.Request(TestURL, data=params,headers={'content-type': 'application/json'})
        response = urllib.request.urlopen(req)
        ResultResponse = response.read().decode('utf8')
        if(len(ResultResponse)>0):
            #print("第" +str(index+1)+"次，response is OK")
            TestEndTime = time.time()
            # print("TestEndTime:"+str(TestEndTime))
            CastTime = TestEndTime - TestStartTime
            print("PID:" + str(ProcessID) + ";第" + str(index + 1) + "次response is OK,耗时" + str(CastTime) + "秒" + "结果长度："+str(len(ResultResponse)))
            TestTimeList.append(CastTime)
        else:
            print("PID:" + str(ProcessID) + ";第" +str(index+1)+"次,response is error")
            break

        time.sleep(0.5)

    AverageCostTime = np.mean(TestTimeList)
    print("PID:" + str(ProcessID) + ";共"+str(TestTimes)+"次"+"平均耗时:"+str(AverageCostTime) + "秒" )


def info(title):
    print("title:", title)
    print('parent process:', os.getppid())
    print('process id:', os.getpid())


def f(name):
    info('function f')
    print('hello', name)


if __name__ == "__main__":
    p_list = []
    for i in range(3):
        p = Process(target=IOVPerformanceTest, args=(TestType,))
        p_list.append(p)
        p.start()
    for i in p_list:
        p.join()
    #print('end')
    '''
    IOVPerformanceTest()
    info('main process line')
    time.sleep(1)
    print("------------------")
    p = Process(target=IOVPerformanceTest, args=('status',))
    p.start()
    p.join()
    '''
